package com.zlsy.learning.leetcode.binarysearch;

/**
 * @author zhouliang
 * @date 2020/10/13 16:00
 */
public class BsearchDemo3 {

  /** 查找最后一个值等于给定值的元素 */
  private static int bsearch(int[] a, int n, int value) {
    int low = 0;
    int hight = n - 1;
    while (low <= hight) {
      int mid = low + ((hight - low) >> 1);
      if (a[mid] > value) {
        hight = mid - 1;
      } else if (a[mid] < value) {
        low = mid + 1;
      } else {
        if (mid == (n - 1) || a[mid + 1] != value) {
          return mid;
        } else {
          low = mid + 1;
        }
      }
    }
    return -1;
  }

  public static void main(String[] args) {
      int[] a = new int[] {1, 3, 4, 5, 6, 8, 8, 8, 11, 18};
      int n = a.length;
      int value = 8;
      System.out.println(bsearch(a, n, value));
  }
}
